package com.geek.health.job;

import com.geek.factory.constant.RedisImgConstant;
import com.geek.factory.service.strategy.FileUploadContext;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/6/30
 */
@Slf4j
public class CleanImgJob extends QuartzJobBean {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private FileUploadContext fileUploadContext;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info(LocalDateTime.now() + "----------- 定时清除 CleanImgJob 图片 ----------");

        //清除图片的平台   Redis使用Set集合差集
        Set<Object> set = redisTemplate.opsForSet().difference(RedisImgConstant.UPLOAD_PIC, RedisImgConstant.UPLOAD_DB_PIC);
        if(!CollectionUtils.isEmpty(set)){
            for (Object o : set) {
                String img = (String) o;
                //获取当前图片所在的平台信息  qiniu   aliyun
                String provider = redisTemplate.opsForValue().get(img + "_provider").toString();
                //删除图片
                boolean flag = fileUploadContext.delete(img, provider);
                if(flag){
                    //在Redis中删除图片信息
                    redisTemplate.delete(img + "_provider");
                    redisTemplate.opsForSet().remove(RedisImgConstant.UPLOAD_PIC , img);
                    log.info("删除图片：{} ， 所在平台:{}" , img , provider);
                }
            }
        }
    }
}
